<template>

  <v-card
    class="mx-auto"
    max-width="600"
  >

      <v-toolbar density="compact"
                 variant="solo"
      >
        <!--      <v-btn variant="text" icon="mdi-magnify"></v-btn>-->
        <v-text-field
          v-model="tempTitle"
          density="compact"
          variant="solo"
          clearable
          hide-details="auto"
          label="Title"
          @click:clear="searchFiles"
        ><template v-slot:append-inner>
          <v-btn density="compact"
                  icon="mdi-file-plus" @click="addFile"></v-btn>
        </template></v-text-field>

      </v-toolbar>

    <div class="fileList" >
      <v-list lines="two" density="compact"    v-model="selectedItemId">

        <v-list-item density="compact"

                     v-for="f in files"
                     :key="f.id"
                     :title="f.title"
                     :subtitle="f.updated.toLocaleString()"
                     :value="f.id"
                     :toggleable="false"

                     @click="editFile(f)"
                     active-color="primary"
        >
          <template v-slot:prepend>
            <v-avatar color="grey">
              <v-icon color="white">mdi-clipboard-text</v-icon>
            </v-avatar>
          </template>

          <template v-slot:append>
            <v-btn
              color="grey-lighten-1"
              icon="mdi-trash-can"
              variant="text"
              @click.stop="deleteFile(f.id)"
            ></v-btn>
          </template>
        </v-list-item>
      </v-list>
    </div>




  </v-card>
</template>
<script>
import {inject, ref,watch} from 'vue';
import {v4 as uuidv4} from 'uuid';
import {openDB} from 'idb';

export default {
  name: 'FileList',
  components: {},

  setup() {

    const DB_NAME = 'file-db';
    const STORE_NAME = 'file-store';

    const dbPromise = openDB(DB_NAME, 1, {
      upgrade(db) {
        const objectStore = db.createObjectStore(STORE_NAME, {keyPath: 'id'});
        objectStore.createIndex('title', 'title');
        objectStore.createIndex('created', 'created');
        objectStore.createIndex('updated', 'updated');
      },
    });
    const IndexedDB = {

      async getAllFiles() {
        const db = await dbPromise;
        const tx = db.transaction(STORE_NAME, 'readonly');
        const store = tx.objectStore(STORE_NAME);
        return store.getAll();
      },
      async addFile(file) {
        const db = await dbPromise;
        const tx = db.transaction(STORE_NAME, 'readwrite');
        const store = tx.objectStore(STORE_NAME);
        const id = uuidv4();
        await store.add({...file, id, created: new Date(), updated: new Date()});
        return tx.complete;
      }
      ,

      async updateFile(file) {
        const db = await dbPromise;
        const tx = db.transaction(STORE_NAME, 'readwrite');
        const store = tx.objectStore(STORE_NAME);
        const updatedFile = {...file, updated: new Date()};
        await store.put(updatedFile);
        return tx.complete;
      }
      ,

      async deleteFile(id) {
        const db = await dbPromise;
        const tx = db.transaction(STORE_NAME, 'readwrite');
        const store = tx.objectStore(STORE_NAME);
        await store.delete(id);
        return tx.complete;
      }
      ,

      async searchFiles(query) {
        const db = await dbPromise;
        const tx = db.transaction(STORE_NAME, 'readonly');
        const store = tx.objectStore(STORE_NAME);
        const index = store.index('title');
        const results = await index.getAll(IDBKeyRange.bound(query, query + '\uffff'));
        return results;
      }
    }

    function quickSort(arr) {
      if (arr.length <= 1) {
        return arr;
      }

      const pivotIndex = Math.floor(arr.length / 2);
      const pivot = arr[pivotIndex];
      const less = [];
      const greater = [];

      for (let i = 0; i < arr.length; i++) {
        if (i === pivotIndex) {
          continue;
        }
        if (arr[i].created > pivot.created) {
          less.push(arr[i]);
        } else {
          greater.push(arr[i]);
        }
      }

      return [...quickSort(less), pivot, ...quickSort(greater)];
    }

    const file = inject('file')

    const files = ref([]);
    const query = ref('');
    const selectedItemId=ref('')

    const tempTitle = ref('');

    watch(tempTitle,(tempTitle, prevtempTitle) => {
      searchFiles(tempTitle?tempTitle:'')
      console.log(tempTitle+':'+prevtempTitle)
    })


    const emptyFile = {
      id: '',
      title: tempTitle,
      description: '',
      type: '',
      prompt: '',
      nPrompt: '',
    }


    const fetchFiles = async () => {

      // const fileList=[]
      // const c = IndexedDB.getAllFilesByUpdated()
      // c.then(value => iterateCursor(value,fileList))

      files.value = quickSort(await IndexedDB.getAllFiles())


    };

    const searchFiles = async () => {

      files.value = quickSort(await IndexedDB.searchFiles(tempTitle.value?tempTitle.value:''));

    };

    const addFile = () => {
      if (file.value.id != '') {
        saveFile();
      }
      file.value = {...emptyFile};
      saveFile();
    };

    const editFile = (item) => {
      if (file.value.id != '') {
        console.log("edit")
        saveFile();
      }

      if(file.value.id!=item.id){
        selectedItemId.value=item.id
        item.updated=new Date()
        file.value = item;
      }

    };

    const deleteFile = async (id) => {
      await IndexedDB.deleteFile(id);
      file.value = {...emptyFile}
      console.log("delete")
      await fetchFiles();
    };

    const saveFile = async () => {


      const newFile = {
        id: file.value.id || uuidv4(),
        title: file.value.title || 'NEW DATA',
        description: file.value.description,
        type: file.value.type,
        prompt: file.value.prompt,
        nPrompt: file.value.nPrompt,
        created: file.value.id ? file.value.created : new Date().toISOString(),
        updated: new Date().toISOString(),
      };


      console.log("save:")
      console.log(newFile)

      await IndexedDB.updateFile(newFile);

      await fetchFiles();
    };




    fetchFiles();

    return {
      files,
      query,
      searchFiles,
      addFile,
      editFile,
      deleteFile,
      saveFile,
      file,
      tempTitle,
      selectedItemId

    };
  },
};
</script>


